//index.js
//获取应用实例
const app = getApp();
const recorderManager = wx.getRecorderManager();
var QQMapWX = require('../../../libs/qqmap-wx-jssdk.js');
var common = require('../../../libs/common.js');
var md5 = require('../../../libs/md5.js');
var qqmapsdk;
var myaudio = wx.createInnerAudioContext();

Page({
  data: {
    
    index: '',//
    luyinpop: false,//css
    luyinzhong: true,//css
    is_clock: false,
    startPoint: '',
    files: [],//图片路径
    videosrc: [],//视频
    chooseimg: false,
    choosevideo: false,
    yiluyin: false,
    yuyinsrc: [],
    luyintime: [],
    dialogShow: false,
    showOneButtonDialog: false,
    buttons: [{ text: '取消' }, { text: '确定' }],
    oneButton: [{ text: '确定' }],
    playing: [],
    setinter: '',
    oneche: false,
    detail: '',
    tixingshow: false,
    videofrom: '',
    previewvideo: false,
    demand_id:''
  },

  onLoad: function (options) {
    var demand_id= options.id;
    this.setData({
      demand_id:demand_id
    })
    // this.qqmap();
    this.luyin = this.selectComponent("#luyin");
  },
  onShow: function () {
    // this.onLoad();
  },

  /******语音描述-录音******/
  luyintap: function (e) {
    this.luyin.luyin();
  },

  // 开始录音
  handleRecordStart: function (e) {
    this.setData({
      is_clock: true,//长按时应设置为true，为可发送状态
      startPoint: e.detail.e.touches[0],//记录触摸点的坐标信息
      luyinzhong: true,//录音跳动
    })
    //设置录音参数
    const options = {
      duration: 300000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 48000,
      format: 'mp3'
    }
    //开始录音
    recorderManager.start(options);
    console.log('start');
  },
  // 松开发送
  handleRecordStop: function (e) {
    recorderManager.stop()//结束录音

    var that = this
    console.log(that.data.is_clock)
    //此时先判断是否需要发送录音


    //对停止录音进行监控
    recorderManager.onStop((res) => {
      //对录音时长进行判断，少于2s的不进行发送，并做出提示
      if (that.data.is_clock == true) {
        if (res.duration < 2000) {
          wx.showToast({
            title: '录音时间太短，请长按录音',
            icon: 'none',
            duration: 1000
          })
        } else {
          var yuyinsrc = res.tempFilePath;
          var luyintime = Math.floor(res.duration / 1000);
          var timestamp = Date.parse(new Date()) / 1000;
          var random = Math.floor(Math.random() * 100);
          var sign = 'GHRDY65' + String(random) + String(timestamp);
          sign = md5.hexMD5(sign);
          wx.showLoading({
            title: '上传中',
          })
          wx.uploadFile({
            url: app.static.url + 'api/common/uploadFile',
            filePath: yuyinsrc,
            name: 'file',
            formData: {
              timestamp: timestamp,
              random: random,
              sign: sign
            },
            success: function (e) {
              console.log(e);
              var data = e.data;
              data = JSON.parse(data);
              var yuyins = that.data.yuyinsrc.concat(data.data.url);
              console.log(yuyins)
              wx.hideLoading()
              that.setData({
                yuyinsrc: that.data.yuyinsrc.concat(data.data.url),
                luyintime: that.data.luyintime.concat(luyintime),
                playing: that.data.playing.concat(0),
                yiluyin: true
              });
            }
          })

        }
      } else {

        console.log('不发送')
      }

    })
  },
  // 滑动取消发送
  handleTouchMove: function (e) {
    //计算距离，当滑动的垂直距离大于25时，则取消发送语音
    if (Math.abs(e.detail.touches[0].clientY - this.data.startPoint.clientY) > 30) {
      this.setData({
        is_clock: false,//设置为不发送语音
        luyinpop: false,
        luyinzhong: false
      })
    }
    console.log('move')
  },
  // 播放录音
  playluyin: function (e) {
    console.log(e)
    var datasrc = e.currentTarget.dataset.src;
    var index = e.currentTarget.dataset.index;
    var that = this;
    var playing = that.data.playing;
    for (var i = 0; i < playing.length; i++) {
      playing[i] = 0;
    }
    myaudio.pause();
    myaudio.src = datasrc;

    if (playing[index] == 0) {
      myaudio.play();
      playing[index] = 1;
      that.setData({
        playing: playing
      })
      myaudio.onEnded(function () {
        console.log(1)
        playing[index] = 0;
        that.setData({
          playing: playing
        })
      })
    } else {
      myaudio.pause();
      playing[index] = 0;
      that.setData({
        playing: playing
      })
    }

  },

  delluyin: function (e) {
    var that = this;
    var yuyin = that.data.yuyinsrc;
    var luyintime = that.data.luyintime;
    var index = e.currentTarget.dataset.index; //获取当前按图片下标
    wx.showModal({
      title: '提醒',
      content: '确定要删除此录音吗？',
      success: function (res) {
        if (res.confirm) {
          yuyin.splice(index, 1);
          luyintime.splice(index, 1);
        } else if (res.cancel) {
          return false;
        }

        that.setData({
          yuyinsrc: yuyin,
          luyintime: luyintime
        });
      }
    })
  },

  /****** 选择视频 ******/
  choosevideo: function () {
    
      this.uploadvideo();
    
  },
  uploadvideo: function () {
    var that = this;
    var videosrc = that.data.videosrc;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      sizeType: ['original', 'compressed'],
      maxDuration: 60,
      camera: 'back',
      success(res) {
        console.log(res.tempFilePath);
        if (wx.showLoading) {
          wx.showToast({
            icon: 'loading',
            title: '请稍候…',
            mask: true
          })
        };
        var timestamp = Date.parse(new Date()) / 1000;
        var random = Math.floor(Math.random() * 100);
        var sign = 'GHRDY65' + String(random) + String(timestamp);
        sign = md5.hexMD5(sign);
        wx.uploadFile({
          url: app.static.url + 'api/common/uploadFile',
          filePath: res.tempFilePath,
          name: 'file',
          formData: {
            timestamp: timestamp,
            random: random,
            sign: sign
          },
          success: function (res) {
            console.log(res);

            wx.hideLoading();
            var data = res.data;
            data = JSON.parse(data);
            if (data.code == 1) {
              that.setData({
                videosrc: that.data.videosrc.concat(data.data.url),
                choosevideo: true
              });
            } else {
              wx.showToast({
                icon: 'none',
                title: data.msg,
                mask: true
              })
            }
          }
        })
        
      }
    })
  },

  // 视频删除效果
  closedel: function (e) {
    var that = this;
    var video = that.data.videosrc;
    var index = e.currentTarget.dataset.index; //获取当前按图片下标
    wx.showModal({
      title: '提醒',
      content: '确定要删除此视频吗？',
      success: function (res) {
        if (res.confirm) {
          video.splice(index, 1);
        } else if (res.cancel) {
          return false;
        }
        that.setData({
          videosrc: video
        });
      }
    })

  },
  //长按图片视频
  deleteVideo: function (e) {
    var that = this;
    var video = that.data.videosrc;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    wx.showModal({
      title: '提醒',
      content: '确定要删除此视频吗？',
      success: function (res) {
        if (res.confirm) {
          video.splice(index, 1);
        } else if (res.cancel) {
          return false;
        }
        that.setData({
          videosrc: video
        });
      }
    })
  },
  /*** 选择图片 ***/
  // 添加图片
  chooseImage: function (e) {
    
      var that = this;
      var images = that.data.files;
      var timestamp = Date.parse(new Date()) / 1000;
      var random = Math.floor(Math.random() * 100);
      var sign = 'GHRDY65' + String(random) + String(timestamp);
      sign = md5.hexMD5(sign);
      wx.chooseImage({
        count: 9 - images.length,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          that.setData({
            chooseimg: true
          })
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          for (var i = 0; i < res.tempFilePaths.length; i++) {
            wx.uploadFile({
              url: app.static.url + 'api/common/uploadFile',
              filePath: res.tempFilePaths[i],
              name: 'file',
              formData: {
                timestamp: timestamp,
                random: random,
                sign: sign
              },
              success: function (ret) {
                console.log(ret)
                var data = ret.data;
                data = JSON.parse(data);
                if (data.code == 1) {
                  that.setData({
                    files: that.data.files.concat(data.data.url),

                  });
                }
              }
            })
          }
        }
      })
    
  },
  // 预览图片
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id,
      urls: this.data.files
    })
  },
  //长按图片删除
  deleteImage: function (e) {
    var that = this;
    var images = that.data.files;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    wx.showModal({
      title: '提醒',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          images.splice(index, 1);
        } else if (res.cancel) {
          return false;
        }
        that.setData({
          files: images
        });
      }
    })
  },
  // 图片删除效果
  closeClick: function (e) {
    var that = this;
    var images = that.data.files;
    var index = e.currentTarget.dataset.index; //获取当前按图片下标
    wx.showModal({
      title: '系统提醒',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          images.splice(index, 1);
        } else if (res.cancel) {
          return false;
        }
        that.setData({
          files: images
        });
      }
    })

  },
  // 预览图片
  preview: function (e) {
    var index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.files[index], // 当前显示图片的http链接  
      urls: this.data.files // 需要预览的图片http链接列表  
    })
  },
  // 预览音频
  previewVideo(e) {
    var videofrom = e.currentTarget.dataset.videofrom;
    this.setData({
      previewvideo: true,
      videofrom: videofrom
    })
  },
 
  // 需求提交
  xqtijiao: function (e) {
    var param = {};
    var description = e.detail.value.xiuchetext;
    var address = this.data.address;
    var imgs = this.data.files;
    var video = this.data.videosrc;
    var voice = this.data.yuyinsrc;
    var voice_len = this.data.luyintime;
    var demand_id = this.data.demand_id;
    if (voice.length == 0 && imgs.length == 0 && video.length == 0 && description == '') {
      wx.showToast({
        title: '请填写至少一种描述',
        icon: 'none',
        duration: 2000
      })
      return false;
    } else {
      
      var imgs = imgs.join(",");
      var video = video.join(",");
      var voice = voice.join(",");
      var voice_len = voice_len.join(",");
      var param = {
        demand_id:demand_id,
        description: description,
        imgs: imgs,
        voice_len: voice_len,
        video: video,
        voice: voice,

      };
      // wx.showLoading({
      //   title: '提交中，请耐心等待。。。'
      // })
      if (wx.showLoading) {
        wx.showToast({
          icon: 'loading',
          title: '提交中，请耐心等待。。。',
          mask: true
        })
      };

      var that = this;
      var xuqiu = {
        url: "api/index/supplement",
        data: param,
        success: function (e) {
          console.log(e);
          that.setData({
            tixingshow: true
          })
          wx.hideLoading()
          myaudio.stop();
          if (e.data.code == 1) {
            wx.switchTab({
              url: '/pages/index/index/index',
            })
          }
        }
      }
      app.post(xuqiu);

    }


  },
  taptixing: function (e) {
    console.log(e);
    this.setData({
      tixingshow: false
    })
  },
  // 视频预览关闭
  hideVideo: function () {
    this.setData({
      previewvideo: false
    })
  },
 
})
